/*
 * @Author: hongbin
 * @Date: 2022-12-24 13:15:54
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-24 20:59:06
 * @Description:
 */
import { FC, useCallback, useEffect, useState } from "react";
import styled, { css } from "styled-components";
import { get, post } from "../../../api";
import { useAuth } from "../../../context/AuthProvide";
import { Button, FlexDiv, hiddenCss, showCss } from "../../../styled";
import { FixedBtnCss } from "../../../styled/help";
import { mongoIDToDateTime } from "../../../utils";
import { Close } from "../../Icon";
import useAddFriendHook from "../FriendsList/useAddFriendHook";

interface IProps {}

interface IItem {
    _id: string;
    senderId: string;
    senderName: string;
    targetId: string;
    /**
     * 这条申请的结果 未处理 通过 拒绝
     */
    result?: "pass" | "reject";
}

/**
 * 好友申请记录
 */
const RequestList: FC<IProps> = () => {
    const { user } = useAuth();
    const addFriend = useAddFriendHook();
    const [open, setOpen] = useState(false);
    const [list, setList] = useState<IItem[]>([]);

    const query = useCallback(async () => {
        const { data } = await get<{ data: IItem[] }>(`/RequestList/query?id=${user._id}`);
        console.log(data);
        setList(data.reverse());
    }, [user._id]);

    useEffect(() => {
        open && query();
    }, [open, query]);

    const setResultState = useCallback((_id: string, result: IItem["result"]) => {
        setList((l) => [...l].map((i) => ({ ...i, result: i._id == _id ? result : i.result })));
    }, []);

    const agreeRequest = useCallback(
        async (r: IItem) => {
            //更改本条请求记录的result字段
            const { data } = await post<{ data: IItem[] }>(`/RequestList/setResult`, {
                requestId: r._id,
                result: "pass",
            });
            console.log(data);

            //添加双方至其好友列表
            if (!data) return;
            addFriend(r.senderId, (isSuccess) => {
                if (isSuccess) return setResultState(r._id, "pass");

                post<{ data: IItem[] }>(`/RequestList/setResult`, {
                    requestId: r._id,
                    result: "",
                });
            });
        },
        [addFriend, setResultState]
    );

    const rejectRequest = useCallback(
        async (r: IItem) => {
            const { data } = await post<{ data: IItem[] }>(`/RequestList/setResult`, {
                requestId: r._id,
                result: "reject",
            });
            data && setResultState(r._id, "reject");
        },
        [setResultState]
    );

    return (
        <Container>
            <Title onClick={() => setOpen(true)}>
                好友 <wbr></wbr> 申请
            </Title>
            <Plane open={open}>
                <Close onClick={() => setOpen(false)} />
                <List list={list} agreeRequest={agreeRequest} rejectRequest={rejectRequest} />
            </Plane>
        </Container>
    );
};

export default RequestList;

const List = ({
    list,
    agreeRequest,
    rejectRequest,
}: {
    list: IItem[];
    agreeRequest: (r: IItem) => void;
    rejectRequest: (r: IItem) => void;
}) => (
    <Main>
        {list.map((r) => (
            <Card key={r._id}>
                <code>{mongoIDToDateTime(r._id)}</code>
                <FlexDiv items="center">
                    <h3>{r.senderName}</h3>
                    <span> 请求添加你为好友</span>
                </FlexDiv>
                {r.result ? (
                    <span>{r.result == "pass" ? "已通过" : "已拒绝"}</span>
                ) : (
                    <FlexDiv justify="space-evenly">
                        <Button bg="#01b027" onClick={() => agreeRequest(r)}>
                            通过
                        </Button>
                        <Button bg="#aa0404" onClick={() => rejectRequest(r)}>
                            拒绝
                        </Button>
                    </FlexDiv>
                )}
            </Card>
        ))}
    </Main>
);

const Container = styled.div``;

const Card = styled.div`
    color: #fffae5;
    padding: 0.4vh;
    margin: 0.4vh 0;
    border-bottom: 1px solid #094102;
    & > code {
        font-size: max(12px, 0.7vw);
        color: #dcd6c2;
    }
    h3 {
        color: #45d424;
        font-size: 1.4vw;
        margin-right: 2px;
    }
    span {
        font-size: 1vw;
    }
`;

const position = css`
    position: fixed;
    bottom: auto;
    top: 1vmax;
    right: auto;
    left: 1vmax;
`;

const Main = styled.main`
    overflow: hidden scroll;
    height: 94%;
    margin-top: 3%;
`;

const Plane = styled.div<{ open: boolean }>`
    ${({ open }) => (open ? showCss : hiddenCss)}
    width: 15vmax;
    height: 20vmax;
    border-radius: 1vmax;
    background: #2f5f1d;
    z-index: 12;
    transition: 0.3s;
    ${position};
    padding: 0 5px;

    & > svg {
        position: absolute;
        right: -1vmax;
        top: -1vmax;
        width: 3vmax;
        height: 3vmax;
        cursor: pointer;
        transition: 0.3s;
        z-index: 1;
        path {
            fill: #fff;
        }
        :hover {
            path {
                fill: #0f0;
            }
        }
    }
`;

const Title = styled.div`
    ${FixedBtnCss};
    ${position};
`;
